using Microsoft.EntityFrameworkCore;

using PandaWebAPI.Models.ef;
using PandaWebAPI.Interfaces;
namespace PandaWebAPI.Services
{
    public class CategoryService : ICategoryService
    {
        private readonly PandaSystemContext _context;

        public CategoryService(PandaSystemContext context)
        {
            _context = context;
        }

        public async Task<IEnumerable<Category>> GetAllCategoriesAsync()
        {
            return await _context.Categories
                .Include(c => c.Posts)
                .ToListAsync();
        }

        public async Task<Category?> GetCategoryByIdAsync(Guid id)
        {
            return await _context.Categories
                .Include(c => c.Posts)
                .FirstOrDefaultAsync(c => c.CategoryId == id);
        }

        public async Task<Category> CreateCategoryAsync(Category category)
        {
            category.CategoryId = Guid.NewGuid();
            
            await _context.Categories.AddAsync(category);
            await _context.SaveChangesAsync();
            
            return category;
        }

        public async Task<Category> UpdateCategoryAsync(Category category)
        {
            var existingCategory = await _context.Categories.FindAsync(category.CategoryId);
            if (existingCategory == null)
                throw new KeyNotFoundException($"Category with ID {category.CategoryId} not found.");

            existingCategory.Name = category.Name;
            existingCategory.Description = category.Description;

            await _context.SaveChangesAsync();
            
            return existingCategory;
        }

        public async Task<bool> DeleteCategoryAsync(Guid id)
        {
            var category = await _context.Categories.FindAsync(id);
            if (category == null)
                return false;

            _context.Categories.Remove(category);
            await _context.SaveChangesAsync();
            
            return true;
        }
    }

    
    
} 